<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import { getMenuListApi, addMenuApi, deleteMenuApi, updateMenuApi } from '@/api/menu'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
// import { ElTag } from 'element-plus'
// import { Icon } from '@/components/Icon'
// import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/MenuWrite.vue'
// import Detail from './components/MenuDetail.vue'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'
import { ElMessage, ElMessageBox } from 'element-plus'
const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    let res = await getMenuListApi()
    let list = res.data || []
    // list.forEach((item) => {
    //   if (item.submenus) {
    //     item.children = [...item.submenus]
    //   } else {
    //     item.children = []
    //   }
    // })
    return {
      list: list || [] //.list
    }
  }
})

const { dataList, loading } = tableState
const { getList } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('userDemo.index'),
    type: 'index'
  },
  {
    field: 'name',
    label: t('menu.menuName')
    // ,
    // slots: {
    //   default: (data: any) => {
    //     const title = data.row.meta.name
    //     return <>{title}</>
    //   }
    // }
  },
  {
    field: 'icon',
    label: t('menu.icon')
    // ,
    // slots: {
    //   default: (data: any) => {
    //     const icon = data.row.meta.icon
    //     if (icon) {
    //       return (
    //         <>
    //           <Icon icon={icon} />
    //         </>
    //       )
    //     } else {
    //       return null
    //     }
    //   }
    // }
  },
  // {
  //   field: 'meta.permission',
  //   label: t('menu.permission'),
  //   slots: {
  //     default: (data: any) => {
  //       const permission = data.row.meta.permission
  //       return permission ? <>{permission.join(', ')}</> : null
  //     }
  //   }
  // },
  //   {
  //     field: 'component',
  //     label: t('menu.component'),
  //     slots: {
  //       default: (data: any) => {
  //         const component = data.row.component
  //         return <>{component === '#' ? '顶级目录' : component === '##' ? '子目录' : component}</>
  //       }
  //     }
  //   },
  {
    field: 'menuPath',
    label: t('menu.path')
  },
  {
    field: 'menuLevel',
    label: t('menu.MenuLevel')
  },
  {
    field: 'menuOrder',
    label: t('menu.MenuOrder')
  },
  {
    field: 'remark',
    label: t('menu.Remark')
  },
  //   {
  //     field: 'status',
  //     label: t('menu.status'),
  //     slots: {
  //       default: (data: any) => {
  //         return (
  //           <>
  //             <ElTag type={data.row.status === 0 ? 'danger' : 'success'}>
  //               {data.row.status === 1 ? t('userDemo.enable') : t('userDemo.disable')}
  //             </ElTag>
  //           </>
  //         )
  //       }
  //     }
  //   },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 240,
    align: 'center',
    fixed: 'right',
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton type="primary" onClick={() => action(row, 'edit')}>
              {t('exampleDemo.edit')}
            </BaseButton>
            {/* <BaseButton type="success" onClick={() => action(row, 'detail')}>
              {t('exampleDemo.detail')}
            </BaseButton> */}
            <BaseButton type="danger" onClick={() => action(row, 'del')}>
              {t('exampleDemo.del')}
            </BaseButton>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'meta.title',
    label: t('menu.menuName'),
    component: 'Input'
  }
])

const searchParams = ref({})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const action = (row: any, type: string) => {
  if (type == 'del') {
    //删除
    ElMessageBox.confirm(t('tips.deltitle'), t('common.delWarning'), {
      confirmButtonText: t('common.ok'),
      cancelButtonText: t('common.cancel'),
      type: 'warning',
      center: true
    }).then(async () => {
      const res = await deleteMenuApi(row)
      if (res.code == 0) {
        saveLoading.value = false
        dialogVisible.value = false
        getList()
      } else {
        saveLoading.value = false
        ElMessage({ type: 'error', message: res?.msg || t('common.opError') })
      }
    })

    return
  }
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  console.log(formData)
  if (formData) {
    saveLoading.value = true
    if (!currentRow.value && !formData?.Guid) {
      formData.Guid = '       '
    } else {
      formData.Guid = currentRow.value.guid
    }
    if (formData.parentGuid) {
      formData.menuLevel = 2
    }
    let res
    if (currentRow.value) {
      res = await updateMenuApi(formData)
    } else {
      res = await addMenuApi(formData)
    }

    if (res.code == 0) {
      saveLoading.value = false
      dialogVisible.value = false
      getList()
    } else {
      ElMessage({ type: 'error', message: res.msg || t('common.opError') })
    }
  }
}
</script>

<template>
  <ContentWrap>
    <!-- <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" /> -->
    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
    </div>
    <!--  node-key="guid" -->
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :columns="tableColumns"
      default-expand-all
      row-key="guid"
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
      :max-height="650"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :current-row="currentRow" />

    <!-- <Detail v-if="actionType === 'detail'" :current-row="currentRow" /> -->

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
